<?php
/**
 * Created by PhpStorm.
 * User: 郑好
 * Date: 2019/7/1
 * Time: 上午9:42
 */

namespace app\common;

class EasyArrayTool
{
    use InstanceTrait;

    // 阶乘
    private function factorial($n)
    {
        return array_product(range(1, $n));
    }

    // 排列数
    private function sort($n, $m)
    {
        return $this->factorial($n) / $this->factorial($n - $m);
    }

    // 排列
    public function arrangement($array, $num)
    {
        $r = array();

        $n = count($array);
        if ($num <= 0 || $num > $n) {
            return $r;
        }

        for ($i = 0; $i < $n; $i++) {
            $b = $array;
            $t = array_splice($b, $i, 1);
            if ($num == 1) {
                $r[] = $t;
            } else {
                $c = $this->arrangement($b, $num - 1);
                foreach ($c as $v) {
                    $r[] = array_merge($t, $v);
                }
            }
        }

        return $r;
    }

    // 按位排列
    public function arrangementByLine($array, $level = 0)
    {
        $r = array();

        // 总行数
        $s = count($array);

        // 跳出
        if ($level < 0 || $level > $s - 1) {
            return $r;
        }

        // 每行计数
        $n = count($array[$level]);
        // 当前行
        $b = $array[$level];

        for ($i = 0; $i < $n; $i++) {
            $t = [$b[$i]];
            if ($level == $s - 1) {
                $r[] = $t;
            } else {
                $c = $this->arrangementByLine($array, $level + 1);

                foreach ($c as $v) {
                    $r[] = array_merge($t, $v);
                }
            }
        }

        return $r;
    }

    // 组合
    public function combination($array, $num)
    {
        $r = array();

        $n = count($array);
        if ($num <= 0 || $num > $n) {
            return $r;
        }

        for ($i = 0; $i < $n; $i++) {
            $t = array($array[$i]);
            if ($num == 1) {
                $r[] = $t;
            } else {
                $b = array_slice($array, $i + 1);
                $c = $this->combination($b, $num - 1);
                foreach ($c as $v) {
                    $r[] = array_merge($t, $v);
                }
            }
        }

        return $r;
    }

    /**
     * @param       $arr
     *
     * @return      array
     * @description 二维数组 行列置换
     */
    public function reshape($arr)
    {
        $result    = array();
        $countLine = count($arr[0]);
        $countRaw  = count($arr);
        for ($j = 0; $j < $countLine; $j++) {
            $result[$j] = array();//确定转置后的数组有几行
        }
        for ($i = 0; $i < $countRaw; $i++) {
            for ($j = 0; $j < count($arr[$i]); $j++) {
                $result[$j][$i] = $arr[$i][$j];//行列互换
            }
        }
        return $result;
    }
}
